package com.xiaozhen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaozhen.blog.entity.Blog;
import com.xiaozhen.blog.entity.Type;
import com.xiaozhen.blog.mapper.BlogMapper;
import com.xiaozhen.blog.mapper.TypeMapper;
import com.xiaozhen.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @create 2023-04-21 18:48
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据该分类的博客数量，获取前 6 个分类
     * @return
     */
    public List<Type> typeListbByCount() {
        // 取数量最多的前 6 个分类
        LambdaQueryWrapper<Type> typeWrapper = new LambdaQueryWrapper<>();
        typeWrapper.orderByDesc(Type::getCount);
        typeWrapper.last("limit 0,6");
        List<Type> typeList = typeMapper.selectList(typeWrapper);
        return typeList;
    }

    /**
     * 查询所有分类
     * @return
     */
    public List<Type> typeList(){
        List<Type> typeList = typeMapper.selectList(null);
        return typeList;
    }

    /**
     * 根据分类 id 查询博客列表
     * @param pageParam
     * @return
     */
    public Page<Blog> blogPage(Page<Blog> pageParam,Long typeId) {
        LambdaQueryWrapper<Blog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Blog::getTypeId,typeId);
        wrapper.orderByDesc(Blog::getUpdateTime);

        Page<Blog> blogPage = blogMapper.selectPage(pageParam, wrapper);
        List<Blog> records = blogPage.getRecords();
        for (Blog record : records) {
            Type type = typeMapper.selectById(record.getTypeId());
            System.out.println("type = " + type.getName());
            record.setTypeName(type.getName());
            String redisKey = "uvBlog." + record.getId();
            record.setViews((Integer) redisTemplate.opsForValue().get(redisKey));
        }
        blogPage.setRecords(records);
        return blogMapper.selectPage(pageParam,wrapper);
    }

    /**
     * 分页查询所有分类
     * @param page
     * @return
     */
    @Override
    public Page<Type> typePage(Long page) {
        // 如果没有传入参数，那么我们把page定义为第 1 页
        if (page == null) {
            page = 1L;
        }
        // 创建对象，传递分页相关参数，每页记录数为 6
        Page<Type> pageParam = new Page<>(page, 6);
        Page<Type> typePage = typeMapper.selectPage(pageParam,null);
        return typePage;
    }

}
